package com.sxf.common.tools;

import java.text.SimpleDateFormat;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.support.RequestContextUtils;

import com.fasterxml.jackson.databind.ObjectMapper;

public class SpringTools {
	private static ObjectMapper mapper;

	/**
	 * 获取spring上下文(listen的全部ApplicationContext,不包括spring mvc的上下文 )
	 * 
	 * @return
	 */
	public static ApplicationContext getWebApplicationContext() {
		return ContextLoader.getCurrentWebApplicationContext();
	}

	/**
	 * DispatcherServlet(Spring mvc)上下文
	 * 
	 * @param request
	 * @return
	 */
	public static WebApplicationContext getWebApplicationContext(
			ServletRequest request) {
		WebApplicationContext wac = RequestContextUtils
				.getWebApplicationContext(request);
		return wac;
	}

	/**
	 * DispatcherServlet(Spring mvc)上下文
	 * 
	 * @param context
	 * @return
	 */
	public static WebApplicationContext getWebApplicationContext(
			ServletContext context) {
		WebApplicationContext wac = WebApplicationContextUtils
				.getRequiredWebApplicationContext(context);
		return wac;
	}

	/**
	 * 设置json序列化格式
	 * 
	 * @return
	 */
	public static ObjectMapper getObjectMapper() {
		if (mapper == null) {
			mapper = new ObjectMapper();
		
			// mapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS,
			// false);
			// mapper.getSerializationConfig().withDateFormat(
			// new SimpleDateFormat("yyyy-MM-dd"));
			mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
		}
		return mapper;
	}

}
